package com.cnaaa.pay.controller;

import com.cnaaa.pay.entity.Trade;
import com.cnaaa.pay.service.TradeService;
import com.cnaaa.pay.vo.BasicJsonResult;
import com.cnaaa.pay.vo.JqGridParam;
import com.cnaaa.pay.vo.JqGridResult;
import com.cnaaa.pay.vo.TradeStatusVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

/**
 * 2018/10/26 Create by 郭文梁
 * TradeController
 * 订单控制器
 *
 * @author 郭文梁
 * @date 2018/10/26
 */
@Slf4j
@RestController
@RequestMapping("/trade")
public class TradeController {
    private final TradeService tradeService;

    @Autowired
    public TradeController(TradeService tradeService) {
        this.tradeService = tradeService;
    }

    @GetMapping("/list")
    public JqGridResult<Trade> list(JqGridParam param, String tradeNo) {
        if (tradeNo == null) {
            //列出
            Integer page = param.getPage();
            Integer rows = param.getRows();
            List<Trade> data = tradeService.list(page, rows);
            long count = tradeService.getCount();
            long total = count / rows + 1;
            return JqGridResult.of(data)
                    .page(page)
                    .records(count)
                    .total((int) total);
        } else {
            //搜索
            Trade trade = tradeService.searchByTradeNo(tradeNo);
            int size = trade == null ? 0 : 1;
            List<Trade> trades = trade == null ? Collections.emptyList() : Collections.singletonList(trade);
            return JqGridResult.of(trades)
                    .page(1)
                    .records(size)
                    .total(size);
        }
    }

    @GetMapping("/{userId}/list")
    public JqGridResult<Trade> list(JqGridParam param, @PathVariable("userId") Long userId) {
        int page = param.getPage();
        int rows = param.getRows();
        int totalCount = tradeService.getUserTradeCount(userId);
        List<Trade> trades = tradeService.listByUser(userId, page, rows);
        return JqGridResult.of(trades)
                .total(totalCount / rows + 1)
                .records(totalCount)
                .page(page);
    }

    @GetMapping("/{tradeId}/_status")
    public BasicJsonResult<TradeStatusVo> status(@PathVariable("tradeId") String tradeId) {
        TradeStatusVo status = tradeService.status(tradeId);
        if (status == null) {
            return BasicJsonResult.error(1, "交易不存在或已经被销毁");
        }
        return BasicJsonResult.ok(status);
    }
}
